將 pg_restore 與多個轉儲一起使用時管理外鍵 (Managing foreign keys when using pg_restore with multiple dumps)


問題描述

將 pg_restore 與多個轉儲一起使用時管理外鍵 (Managing foreign keys when using pg_restore with multiple dumps)

我有一個奇怪的問題。我們試圖為我們的本地環境創建一個數據庫基線,其中預先植入了非常具體的數據。我們希望確保每個人都使用相同的數據進行操作,從而使協作和審查代碼更簡單一些。

我的想法是,每當我們運行遷移或決定本地開發人員需要一個新帳戶時,運行一個命令來轉儲數據庫。問題是數據庫轉儲約為 17MB。我試圖避免每次更新數據庫時都必須向 GitHub 添加一個 17MB 的文件。

所以我能想到的最佳解決方案是設置一個腳本來轉儲數據庫中的每個單獨的表. 這樣,如果單個表被更新,我們' d 只會將該備份推送到 GitHub,它會更多地沿著 ~200kb 文件而不是 17mb。

我遇到的主要問題是嘗試恢復數據庫。使用完整轉儲,處理外鍵相對簡單,因為這一切都在單個還原命令中完成。但是有多個恢復,它變得有點複雜。

我正在尋找一種方法將所有表還原到數據庫,忽略觸發器和約束,然後在填充數據後再次啟用它們。(或根據定義外鍵的順序找到一種導出表的方法)。有很多表要處理,所以手動執行此操作會有點困難。

我' 如果我禁用/重新啟用約束,我還關心數據庫的關係完整性。任何幫助或建議將不勝感激。

現在我在每個表上運行以下命令:

pg_dump postgres://user:password@pg:5432/database ‑t table_name ‑Fc ‑Z9 ‑f /data/www/database/data/table_name.bak

然後這個命令將所有備份恢復到數據庫。

$data_command = "pg_restore ‑‑disable‑triggers ‑d $dbUrl ‑Fc \"%s\"";
$backups = glob("$directory*.bak");
    foreach($backups as $data_file){
        if($data_file != 'data_roles.bak') {
            exec(sprintf($data_command, $data_file));
        }
    }

這顯然不起作用,因為我遇到了大量“關係不存在”錯誤。我想我只是在尋找一種更好的方法來實現這一點。


參考解法

方法 1:

I would separate the table data and the database metadata.

Create a pre‑ and post‑data scfipt with

pg_dump ‑‑section=pre‑data ‑f pre.sql mydb
pg_dump ‑‑section=post‑data ‑f post.sql mydb

Then dump just the data for each table:

pg_dump ‑‑section=data ‑‑table=tab1 ‑f tab1.sql mydb

To restore the database, first restore pre.sql, then all the table data, then post.sql.

The pre‑ and post‑data will change often, but they are not large, so that shouldn't be a problem.

(by John BakerLaurenz Albe)

參考文件

  1. Managing foreign keys when using pg_restore with multiple dumps (CC BY‑SA 2.5/3.0/4.0)

#pg-dump #cloning #pg-restore #postgresql






相關問題

如何檢查我是否只刪除了所需的數據? (How do I check that I removed required data only?)

無法恢復 pg_dump 備份 (Unable to restore pg_dump backup)

使用帶有 Curl 的緩衝輸出將文件上傳到 ftp 服務器 (Upload a file into a ftp server using buffered output with Curl)

帶有 -C 選項的 pg_restore 不會創建數據庫 (pg_restore with -C option does not create the database)

pg_dump 數據庫轉儲是“當時”轉儲嗎? (Is a pg_dump DB dump 'at-that-time' dump?)

PSQL 數據庫傳輸和錯誤 (PSQL database transfer and errors)

Postgres pg_dump 顯示空文件 (Postgres pg_dump show empty file)

將 pg_restore 與多個轉儲一起使用時管理外鍵 (Managing foreign keys when using pg_restore with multiple dumps)

設計:在不斷創建和刪除表時運行 pg_dump (Design: running pg_dump when tables are continuously created and dropped)

轉儲文件中視圖預定義的目的是什麼 (What is the purpose of views' predefinitions in dump file)

如何附加 pg_dump 備份命令 PostgreSQL 的日誌輸出 (How to append log output of pg_dump backup command PostgreSQL)

PostgreSQL:單個表的 pg_dump (PostgreSQL: pg_dump for a single table)







留言討論